package com.tz.springmvc.framework.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

/**
 * 用于登陆验证的拦截器
 * @author Administrator
 *
 */
public class LoginInterceptor implements HandlerInterceptor {

	//在执行handler方法之前,运行这个方法里面的代码	
	//用户登陆验证
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object arg2) throws Exception {
		System.out.println("进入LoginInterceptor.preHandle()");		
		
		//需要先过滤匿名访问地址
		String url = request.getRequestURI();
		if(url.indexOf("login")>=0){
			return true;
		}
		if(url.indexOf("gotoLogin")>=0){
			return true;
		}
	 	
		//判断session里面是否有登陆信息(登陆成功的时候,将登陆名已经放入session)
		HttpSession session = request.getSession(); 
		String loginName = (String) session.getAttribute("loginName");
	 	if(loginName!=null){ //表示已经登陆过
			return true;
		}else{//没有登陆过
			System.out.println("没有登陆过");
			request.getRequestDispatcher("/login.jsp").forward(request, response);
		}		
		return false;
	}
	
	//在执行handler方法中,返回ModelAndView之前,运行这个方法里面的代码
	//向页面提供一些公用的数据或者视图信息
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object arg2, ModelAndView arg3)
			throws Exception {
		System.out.println("进入LoginInterceptor.postHandle()");
		
	}
	
	//执行handler方法之后,运行这个里面的代码
	//比如:统一的异常处理 
	//计算某个handler方法的执行时间:afterCompletion-preHandler
	//统一的日志记录
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object arg2, Exception arg3)
			throws Exception {
		System.out.println("进入LoginInterceptor.afterCompletion()");
		
	}

	

	

}
